#!/usr/bin/python3

import os
import re
import subprocess
import sys
import time

if __name__ == "__main__":

    FEDORA_VERSION="36"

    WORK_DIR=subprocess.run(["pwd"],stdout=subprocess.PIPE,encoding="utf-8").stdout
    WORK_DIR=WORK_DIR[0:len(WORK_DIR)-len("autotools/")]
    WGET_DIR="https://mirrors.163.com/fedora/releases/"+FEDORA_VERSION+"/Everything/source/tree/Packages/"

    print("\nPWD is:"+WORK_DIR+"  FEDORA_VERSION is:"+FEDORA_VERSION+"\n")

    
    print("输入你想构建的包组名，可选的包有：输入*构建所有包")
    pkggroup=["0","2","3","4","5","6","7","9","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
   
    Firstcodelisttmp= input().split()
    Firstcodelist=[]
    
    if Firstcodelisttmp==["*"] :
        Firstcodelist=pkggroup
    else:
        for i in range(len(Firstcodelisttmp)):
            if Firstcodelisttmp[i]  in pkggroup :
                Firstcodelist.append(Firstcodelisttmp[i])

    print("选中的包组:",Firstcodelist)
    if (Firstcodelist)==[]:
        print("无可用包组，退出程序")
        exit()
    #生成包组列表


    for Firstcode in Firstcodelist:
        FILE_NAME="index.html"
        indexurl=WGET_DIR+Firstcode+"/"
        subprocess.run(["rm",WORK_DIR+Firstcode+"/"+FILE_NAME])
        subprocess.run(["wget","-P"+WORK_DIR+Firstcode,indexurl])

        htmlfile=open(WORK_DIR+Firstcode+"/"+FILE_NAME,'r')
        pkgname_str=[]
        result=[]
        pkgname=[]

        lineslist=htmlfile.readlines()
        for line in lineslist:
            #print(line)l
            for i in range(len(line)) :
                if line[i:i+len(".fc"+FEDORA_VERSION+".src.rpm")]==".fc"+FEDORA_VERSION+".src.rpm" :
                    for j in range(len(line)) :
                        if line[j-5:j] == "href=" :
                            pkgname_str.append(line[j+1:i])
                            #print(line[j+1:i+7])
                            break
                    break
                
        htmlfile.close()


        #保存文件
        #subprocess.run(["mkdir",Firstcode])
        resultfile=open(WORK_DIR+Firstcode+"/"+Firstcode+"_pkglist",'w')

        for i in range(len(pkgname_str)):
            resultfile.write(pkgname_str[i]+(60-len(pkgname_str[i]))*" "+"fc"+FEDORA_VERSION+(10-len("fc"+FEDORA_VERSION))*" "+"Waiting"+"\n")
        resultfile.close()

        print("------------------------------------Tast Over--------------------------------------")
        print("Packages number:"+str(len(pkgname_str))+"\n")
        subprocess.run(["cat",WORK_DIR+"/"+Firstcode+"/"+Firstcode+"_pkglist"])
        print("\nPackages number:"+str(len(pkgname_str))+"\n")

        print("生成文件:"+WORK_DIR+Firstcode+"/"+Firstcode+"_pkglist")

        print('\n')

        time.sleep(3)
